package com.ggb.reactive.service

import com.ggb.reactive.domain.entity.User
import com.ggb.reactive.extension.log
import lombok.RequiredArgsConstructor
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Query
import org.springframework.r2dbc.core.DatabaseClient
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import java.time.LocalDateTime

@Service
@RequiredArgsConstructor
class UserService(private val r2dbcEntityTemplate: R2dbcEntityTemplate,private val databaseClient: DatabaseClient) {

    /**
     * 用户统计
     */
    fun countByMap(begin: LocalDateTime?, end: LocalDateTime?): Mono<Int> {
        val sql = StringBuilder("select count(id) from user where 1=1")


        begin?.let{
            sql.append(" and create_time = :begin")
        }
        end?.let{
            sql.append(" and create_time = :end")
        }


        var spec = databaseClient.sql(sql.toString())


        begin?.let {
            spec = spec.bind("begin", it)
        }
        end?.let {
            spec = spec.bind("end", it)
        }

        return spec.map { row -> row.get("count(id)", Int::class.java) }
            .one()
            .map { sum -> sum ?: 0 } // 如果 sum 为 null，则返回 0.0
            .onErrorResume {
                Mono.just(0) // 返回一个默认值，避免终止流程
            }
    }



    fun findUserByOpenid(openid:String): Mono<User?>{
        val criteria = Criteria.where("openid").`is`(openid)
        return r2dbcEntityTemplate.selectOne(Query.query(criteria), User::class.java)
            .doOnNext { user -> log.info("Found user: $user") }
            .doOnError { error -> log.error("Error finding user by openid: $openid", error) }

    }
}